package so.shanku.essential.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import so.shanku.essential.R;
import so.shanku.essential.activity.*;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.*;
import so.shanku.essential.view.CircleImageView;
import so.shanku.essential.view.PullScrollView;
import so.shanku.essential.view.ScalScrollView;
import so.shanku.essential.view.WihteRoundCornersDialog;
import so.shanku.essential.view.PullScrollView.OnScrollChangedListener;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 我的
 *
 * @author sk06
 * 
 * update by FangDongzhang  on 2016/4/14
 */

public class UserCenterFragment extends BaseFragment implements PullScrollView.OnTurnListener{
    @ViewInject(R.id.scrollview_topic_layout)
    private RelativeLayout relativeLayout;
    /**
     * 我的消息
     */
    @ViewInject(R.id.logo_msg_iv)
    private ImageView logo_msg_iv;
    /**
     * 客服
     */
    @ViewInject(R.id.custom_service_iv)
    private ImageView custom_service_iv;

//    /**
//     * 滚动控件
//     */
//    @ViewInject(R.id.cus_sv)
//    private ScalScrollView mScrollView;

//    @ViewInject(R.id.bg_scale_iv)
//    private ImageView user_center_bg_iv;
    /**
     * 上传头像
     */
    @ViewInject(R.id.iv_taking_pictures)
    private CircleImageView iv_taking_pictures;
//
//    /**
//     * 用户名
//     */
//    @ViewInject(R.id.usernick_tv)
//    private TextView userNick_tv;
//    @ViewInject(R.id.userNickLayout)
//    private RelativeLayout userNickLayout;

//    /**
//     * 个人描述
//     */
//    @ViewInject(R.id.user_dis_tv)
//    private TextView user_dis_tv;
//    @ViewInject(R.id.user_dis_layout)
//    private RelativeLayout user_dis_layout;
    /**
     * 日志
     */
    @ViewInject(R.id.blog_layout)
    private LinearLayout blog_layout;
    @ViewInject(R.id.blog_num_tv)
    private TextView blog_num_tv;
//    /**
//     * 话题
//     */
//    @ViewInject(R.id.topic_layout)
//    private LinearLayout topic_layout;
//    @ViewInject(R.id.topic_num_tv)
//    private TextView topic_num_tv;
    /**
     * 关注
     */
    @ViewInject(R.id.focus_layout)
    private LinearLayout focus_layout;
    @ViewInject(R.id.focus_num_tv)
    private TextView focus_num_tv;
    /**
     * 粉丝
     */
    @ViewInject(R.id.fans_layout)
    private LinearLayout fans_layout;
    @ViewInject(R.id.fans_num_tv)
    private TextView fans_num_tv;
    /**
     * 购物车
     */
    @ViewInject(R.id.myShopCart_layout)
    private LinearLayout myShopCart_layout;
    @ViewInject(R.id.myShopCartNum_tv)
    private TextView myShopCartNum_tv;
    /**
     * 订单
     */
    @ViewInject(R.id.myOrdersLayout)
    private LinearLayout myOrdersLayout;
    @ViewInject(R.id.myOrdersNum_tv)
    private TextView myOrdersNum_tv;
    /**
     * 我的收藏
     */
    @ViewInject(R.id.myCollectionLayout)
    private LinearLayout myCollectionLayout;
    @ViewInject(R.id.myCollectionNum_tv)
    private TextView myCollectionNum_tv;

    /**
     * 我的账户
     */
    @ViewInject(R.id.myAccountLayout)
    private LinearLayout myAccountLayout;
    @ViewInject(R.id.myAccountNum_tv)
    private TextView myAccountNum_tv;
    /**
     * 我的预约
     */
    @ViewInject(R.id.myAppointmentLayout)
    private LinearLayout myAppointmentLayout;
    @ViewInject(R.id.myAppointmentNum_tv)
    private TextView myAppointmentNum_tv;
    /**
     * 系统设置
     */
    @ViewInject(R.id.settingLayout)
    private LinearLayout settingLayout;

    private View viewCamera;
    /**
     * 滚动控件
     */
    @ViewInject (R.id.scroll_view)
    private PullScrollView mScrollView;
    /**
     * 背景图片
     */
    @ViewInject (R.id.usercenter_background_img)
    private ImageView mHeadImg;
    /**
     * 标题
     */
    @ViewInject(R.id.text_center_name)
	TextView text_center_name;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.user_center_layout, container, false);
//        mScrollView = (PullScrollView) view.findViewById(R.id.scroll_view);
//        mScrollView = (PullScrollView) view.findViewById(R.id.scroll_view);
        return view;

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        getServerData();
        relativeLayout.getBackground().setAlpha(0);
		mScrollView.setHeader(mHeadImg);
		mScrollView.setOnTurnListener(this);
		
		mScrollView.setOnScrollChangedListener(new OnScrollChangedListener() {

			@SuppressLint("UseValueOf")
			@Override
			public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
				// TODO Auto-generated method stub
				
				int height = 480;
				if (t < height) {
					text_center_name.setVisibility(View.GONE);
					int alpha = (int) (new Float(t) / new Float(height) * 255);
					relativeLayout.getBackground().setAlpha(alpha);
				} else {
					text_center_name.setVisibility(View.VISIBLE);
					text_center_name.setText("方东");
					relativeLayout.getBackground().setAlpha(255);
				}
			}
		});
		
		
        
//        mScrollView.setImageView(user_center_bg_iv);
        //mScrollView.setOnTouchListener(new TouchListenerImpl());
    }

    @Override
    public void onResume() {
        super.onResume();
        maxImageheight = getResources().getDimensionPixelSize(R.dimen.center_bg_layout_height);
        normalImageHeight = getResources().getDimensionPixelSize(R.dimen.center_bg_layout_height_max);
    }

    private int maxImageheight;
    private int normalImageHeight;
    private TouchTool touchTool;

//    private class TouchListenerImpl implements View.OnTouchListener {
//        @Override
//        public boolean onTouch(View view, MotionEvent motionEvent) {
//            float currentY = motionEvent.getY();
//            switch (motionEvent.getAction()) {
//                case MotionEvent.ACTION_DOWN:
//                case MotionEvent.ACTION_POINTER_DOWN:
//                    touchTool = new TouchTool(0, currentY);
//                    break;
//                case MotionEvent.ACTION_MOVE:
//                    if (touchTool == null) {
//                        touchTool = new TouchTool(0, currentY);
//                    }
//                    int scrollY = view.getScrollY();
//                    int height = view.getHeight();
//                    int scrollViewMeasuredHeight = mScrollView.getChildAt(0).getMeasuredHeight();
//                    int distanceY = touchTool.getMoveDistance(currentY);
//                    ViewGroup.LayoutParams params = user_center_bg_iv.getLayoutParams();
//                    LogUtil.d(TAG, "滑动distanceY=" + distanceY);
//                    LogUtil.d(TAG, "old height=" + params.height);
//
//                    if (scrollY == 0) {
//                        LogUtil.d(TAG, "滑动到了顶端 view.getScrollY()=" + scrollY);
//                        if (distanceY <= maxImageheight - normalImageHeight) {
//                            params.height = normalImageHeight + distanceY;
//                            params.width = MyApplication.getInstance().getScreenWidth() + distanceY * 4 / 3;
//                            user_center_bg_iv.setLayoutParams(params);
//                        }
//                    } else {
//                        if (params.height > normalImageHeight) {
//                            params.height = normalImageHeight + distanceY;
//                            params.width = MyApplication.getInstance().getScreenWidth() + distanceY * 4 / 3;
//                            user_center_bg_iv.setLayoutParams(params);
//                        } else {
////                            if ((scrollY + height) == scrollViewMeasuredHeight) {
////                                LogUtil.d(TAG, "滑动到了底部 scrollY=" + scrollY);
////                            }
//                            int topHeight = scrollview_topic_layout.getMeasuredHeight();
//                            if (mScrollView.getTop() - topHeight >= 0) {
//                                LogUtil.d(TAG, "icon over top");
//                                scrollview_topic_layout.setBackgroundResource(R.color.trans_light_gray);
//                            } else {
//                                scrollview_topic_layout.setBackgroundResource(R.color.transparent);
//                            }
//
//                        }
//
//                    }
//                    LogUtil.d(TAG, "current scrollY=" + scrollY);
//                    LogUtil.d(TAG, "current height=" + height);
//                    LogUtil.d(TAG, "current scrollViewMeasuredHeight=" + scrollViewMeasuredHeight);
//                    break;
//                case MotionEvent.ACTION_UP:
//                    // 手指松开.
//                    animation();
//                    break;
//                default:
//
//                    break;
//            }
//            return false;
//        }
//
//    }


    /***
     * 回缩动画
     */
//    public void animation() {
//        touchTool = null;
//        ViewGroup.LayoutParams params = user_center_bg_iv.getLayoutParams();
//        params.height = normalImageHeight;
//        params.width = MyApplication.getInstance().getScreenWidth();
//        user_center_bg_iv.setLayoutParams(params);
//    }


    private void getServerData() {

    }


    /**
     * 找Id
     */
    private void initView(View view) {
        ViewUtils.inject(this, view);
        refreshUserPhotoAndStatue();
    }

    /**
     * 我的消息
     *
     * @param view
     */
    @OnClick(R.id.logo_msg_iv)
    public void logo_msg_iv_click(View view) {
        Intent personData = new Intent(activity, MyMsgActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 联系客服
     *
     * @param view
     */
    @OnClick(R.id.custom_service_iv)
    public void custom_service_iv_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 头像
     *
     * @param view
     */
    @OnClick(R.id.iv_taking_pictures)
    public void iv_taking_pictures_click(View view) {
        showModPhotosView();
    }

    /**
     * 昵称
     *
     * @param view
     */
    @OnClick(R.id.usernick_tv)
    public void usernickLayout_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

//    /**
//     * 个人资料
//     *
//     * @param view
//     */
//    @OnClick(R.id.user_dis_layout)
//    public void user_dis_layout_click(View view) {
//        Intent personData = new Intent(activity, UserDataActivity.class);
//        startActivityForResult(personData, personcenter);
//    }

    /**
     * 日志
     *
     * @param view
     */
    @OnClick(R.id.blog_layout)
    public void blog_layout_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

//    /**
//     * 话题
//     *
//     * @param view
//     */
//    @OnClick(R.id.topic_layout)
//    public void topic_layout_click(View view) {
//        Intent personData = new Intent(activity, UserDataActivity.class);
//        startActivityForResult(personData, personcenter);
//    }

    /**
     * 关注
     *
     * @param view
     */
    @OnClick(R.id.focus_layout)
    public void focus_layout_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 粉丝
     *
     * @param view
     */
    @OnClick(R.id.fans_layout)
    public void fans_layout_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 购物车
     *
     * @param view
     */
    @OnClick(R.id.myShopCart_layout)
    public void myShopCart_layout_click(View view) {
        activity.jumpToShopCart();
    }

    /**
     * 我的订单
     *
     * @param view
     */
    @OnClick(R.id.myOrdersLayout)
    public void myOrdersLayout_click(View view) {
        //全部订单
        Intent personOrder = new Intent(activity, UserOrderActivity.class);
        startActivity(personOrder);
    }

    /**
     * 我的搜藏
     *
     * @param view
     */
    @OnClick(R.id.myCollectionLayout)
    public void myCollectionLayout_click(View view) {
        Intent personCollection = new Intent(activity, UserCollectionActivity.class);
        startActivity(personCollection);
    }

    /**
     * 我的预约
     *
     * @param view
     */
    @OnClick(R.id.myAppointmentLayout)
    public void myAppointmentLayout_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 我的账户
     *
     * @param view
     */
    @OnClick(R.id.myAccountLayout)
    public void myAccountLayout_click(View view) {
        Intent personData = new Intent(activity, MyAccountActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 系统设置
     *
     * @param view
     */
    @OnClick(R.id.settingLayout)
    public void settingLayout_click(View view) {
        Intent personData = new Intent(activity, SetActivity.class);
        startActivity(personData);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        refreshUserPhotoAndStatue();
    }

    /**
     * 刷新头像和信息
     */
    private void refreshUserPhotoAndStatue() {
//        user_dis_tv.setText(Utils.getUserDiscri(activity));
//        userNick_tv.setText(Utils.getUserNickNameOrAccount(activity));
//        ImageLoader.getInstance().displayImage(Utils.getUserPic(activity), iv_taking_pictures, MyApplication.getInstance().getUserHeadOption(), new ImageLoaderBitmapCallBack());
    }


    /**
     * “我的”点击事件
     */
    View.OnClickListener myclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int id = v.getId();
            switch (id) {
                case R.id.select_v:
                    popupWindow.dismiss();
                    break;

                case R.id.bt_my_log_out:
                    //退出登录
                    showExitDialog();
                    break;

                default:
                    break;
            }
        }
    };

    /**
     * 退出dialog
     */
    WihteRoundCornersDialog builder;

    private void showExitDialog() {
        builder = new WihteRoundCornersDialog(activity,
                R.style.ExitDialogStyle, 2, callBackdialog);
        builder.setTitletext(R.string.app_version_prompt);
        builder.setMessagetext(R.string.change_user);
        builder.setButtonText(R.string.cancel, R.string.ensure);
        builder.show();
    }

    private WihteRoundCornersDialog.DialogCallBack callBackdialog = new WihteRoundCornersDialog.DialogCallBack() {

        @Override
        public void bttonclick(int index) {
            builder.dismiss();
            switch (index) {
                case 1:

                    break;
                case 2:
                    clearUserBindTag();
                    Utils.clearUserInfoData(activity);
                    MyApplication.getInstance().setAttentionBrands(null);
                    MyApplication.getInstance().setPushMsgCount(0);
                    MyApplication.getInstance().setShopcart_num(0);
                    Intent intentLogin = new Intent(activity, NoLoginActivity.class);
                    intentLogin.putExtra(ExtraKeys.Key_Msg1, 0);
                    activity.jumpTo(intentLogin, true);

                    break;
                default:
                    break;
            }
        }

        @Override
        public void bttonclick(int index, int what) {

        }

    };

    private void clearUserBindTag() {
        Map<String, Object> params = new HashMap<String, Object>();

        params.put("userId", Utils.getUserId(activity));
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_LogOut);
        queue.setParamsNoJson(params);
        queue.setCallBack(new IGetServicesDataCallBack() {
            @Override
            public void onLoaded(GetDataQueue entity) {
                LogUtil.d(TAG, entity.getInfo());
            }
        });
        getDataUtil.getData(queue);
    }


    public PopupWindow popupWindow;
    private TextView select_photo_camera_bt;
    private TextView select_photo_local_bt;
    private final int select_local_requestcode = 1;
    private final int select_camera_requestcode = 3;
    private final int crop_requestcode = 4;
    private final int attentionbrand = 7;
    private final int personcenter = 8;//个人中心
    /**
     * 存放照片的文件
     */
    private File image;

    private void showModPhotosView() {
        if (popupWindow == null) {
            View view = activity.getLayoutInflater().inflate(R.layout.select_photo, null);
            popupWindow = new PopupWindow(view,
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.setContentView(view);
            popupWindow.setAnimationStyle(R.style.popupAnimation);
            select_photo_camera_bt = (TextView) view
                    .findViewById(R.id.select_photo_camera_bt);
            select_photo_local_bt = (TextView) view
                    .findViewById(R.id.select_photo_local_bt);
            View select_v = view.findViewById(R.id.select_v);
            select_photo_local_bt.setOnClickListener(cameraClick);
            select_photo_camera_bt.setOnClickListener(cameraClick);
            select_v.setOnClickListener(myclick);
            popupWindow.showAtLocation(iv_taking_pictures, Gravity.NO_GRAVITY, 0, 0);

        } else if (!popupWindow.isShowing()) {
            popupWindow.showAtLocation(iv_taking_pictures, Gravity.NO_GRAVITY, 0, 0);
        }
    }

    private OnClickListener cameraClick = new OnClickListener() {
        @Override
        public void onClick(View view) {
            int id = view.getId();
            if (id == R.id.select_photo_local_bt) {
                Intent intent = CropImage.getImageClipIntent_KITKAT();
                startActivityForResult(intent, select_local_requestcode);

            } else if (id == R.id.select_photo_camera_bt) {
                startCamera(select_camera_requestcode);
            }
            popupWindow.dismiss();
        }
    };

    private void startCamera(int position) {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return;
        }
        File file = new File(Constant.productPath
                + "/MyPhoto");
        if (!file.exists()) {
            file.mkdirs();
        }
        image = new File(file, "myphoto.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));

        startActivityForResult(intent, position);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case personcenter:
                    refreshUserPhotoAndStatue();
                    break;

                case attentionbrand:
                    ((MainActivity) activity).setSelectItem(3);
                    break;

                case select_camera_requestcode:
                    doCropPhoto(Uri.fromFile(image));
                    break;

//                case select_local_requestcode_kitkat:

                case select_local_requestcode:
                /* 将Bitmap设定到ImageView */
                    Uri selectedImage = data.getData();
                    String imagePath = PicHelper.getPath(activity, selectedImage); // 获取图片的绝对路径
                    Uri newUri = Uri.parse("file:///" + imagePath); // 将绝对路径转换为URL
                    doCropPhoto(newUri);
                    break;
                case crop_requestcode:
                    try {
                        /* 将Bitmap设定到ImageView */
                        Bitmap bitmap = data.getParcelableExtra("data");
//						user_photo_iv.setImageBitmap(bitmap);
                        // // 将图片转为string
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                        String uploadBuffer = new String(Base64.encode(
                                baos.toByteArray(), Base64.DEFAULT)); // 进行Base64编码

                        String fileType = "png";
                        upLoadUserPic(uploadBuffer, fileType);
                    } catch (Exception e) {
                        toast.showToast(R.string.user_updata_pic_error);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 上传用户头像 (调用接口)
     */
    private void upLoadUserPic(String fileText, String fileType) {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userName", Utils.getUserAccount(activity));
        params.put("headerPicContent", fileText);
        params.put("headerPicType", fileType);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.GetAction_UpdateUserHeaderPic);
        queue.setParamsNoJson(params);
        queue.setCallBack(new IGetServicesDataCallBack() {
            @Override
            public void onLoaded(GetDataQueue entity) {
                if (entity.isOk()) {
                    if (ShowGetDataError.isOkAndCodeIsNot1(activity,
                            entity.getInfo())) {
                        toast.showToast(R.string.uploading_success);
                        List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
                                entity.getInfo(), JsonKeys.Key_Info);
                        String headerPicPath = data.get(0).getStringNoNull("headerPicPath");
                        ImageLoader.getInstance().displayImage(headerPicPath, iv_taking_pictures, MyApplication.getInstance().getDefaultOption(), new ImageLoaderBitmapCallBack());
                        Utils.saveUserPic(activity, headerPicPath);
                    }
                } else {
                    ShowGetDataError.showNetError(activity);
                }
                loadingToast.dismiss();
            }
        });
        getDataUtil.getData(queue);
    }

    /**
     * 加载剪裁
     */
    protected void doCropPhoto(Uri imageUri) {
        try {
            // 启动gallery去剪辑这个照片
            Intent intent = CropImage.getSquareCropImageIntent(imageUri);
            startActivityForResult(intent, crop_requestcode);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    /**
     * 点击banck见
     *
     * @return
     */
    @Override
    public boolean backKeyClick() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            return true;
        } else {
            return false;
        }
    }

	@Override
	public void onTurn() {
		// TODO Auto-generated method stub
		
	}

}
